package cc.eguid.tools.ui;

import cc.eguid.tools.RemoteServer;
import cc.eguid.tools.FileTransferServer;

import javax.swing.*;
import java.awt.*;
import javax.swing.Timer;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.util.Random;

/**
 * 服务端面板
 */
public class ServerPanel extends JPanel {
    private JTextField portField;
    private JButton startButton, stopButton;
    private JLabel statusLabel;
    private RemoteServer server;
    private FileTransferServer fileTransferServer;
    // 客户端列表 UI
    private JTable clientTable;
    private ClientTableModel clientTableModel;
    private JButton prevPageButton;
    private JButton nextPageButton;
    private JLabel pageLabel;
    private JButton disconnectClientButton;
    private int currentPage = 1;
    private static final int PAGE_SIZE = 5;

    private Timer clientListTimer;
    private String lastShownAddress = "";
    private String lastConnectedAtText = "";

    //令牌
    private JTextField tokenField;
    private JButton generateTokenButton;

    //文件上传
    private JTextField filePortField;
    private JLabel uploadStatusLabel;


    public ServerPanel() {
        setLayout(new BorderLayout());

        // 顶部控制面板
        JPanel controlPanel = new JPanel(new FlowLayout());
        //令牌
        controlPanel.add(new JLabel("令牌:"));
        tokenField = new JTextField(generateRandomToken(), 6);
        controlPanel.add(tokenField);
        generateTokenButton = new JButton("\uD83D\uDD04 生成新令牌");
        controlPanel.add(generateTokenButton);
        generateTokenButton.addActionListener(e -> {
            tokenField.setText(generateRandomToken());
        });

        controlPanel.add(new JLabel("端口:"));
        portField = new JTextField(String.valueOf(RemoteAssistance.DEFAULT_PORT), 3);
        controlPanel.add(portField);

        startButton = new JButton("\uD83D\uDE80 启动服务");
        stopButton = new JButton("\uD83D\uDED1 停止服务");
        stopButton.setEnabled(false);

        controlPanel.add(startButton);
        controlPanel.add(stopButton);

        statusLabel = new JLabel("\uD83D\uDD34 服务未启动");
        controlPanel.add(statusLabel);

        //文件上传
        //添加文件传输端口配置
        controlPanel.add(new JLabel("文件传输端口:"));
        filePortField = new JTextField(String.valueOf(RemoteAssistance.DEFAULT_FILE_TRANSFER_PORT), 5);
        controlPanel.add(filePortField);

        uploadStatusLabel = new JLabel("就绪");
        controlPanel.add(uploadStatusLabel);

        add(controlPanel, BorderLayout.NORTH);

        // 事件监听
        startButton.addActionListener(e -> startServer());
        stopButton.addActionListener(e -> stopServer());



        // 底部：客户端表格 + 分页 + 断开按钮
        JPanel bottomPanel = new JPanel(new BorderLayout());
        clientTableModel = new ClientTableModel();
        clientTable = new JTable(clientTableModel);
        clientTable.setFillsViewportHeight(true);
        JScrollPane scrollPane = new JScrollPane(clientTable);
        bottomPanel.add(scrollPane, BorderLayout.CENTER);

        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        prevPageButton = new JButton("上一页");
        nextPageButton = new JButton("下一页");
        pageLabel = new JLabel("第 1 页");
        paginationPanel.add(prevPageButton);
        paginationPanel.add(nextPageButton);
        paginationPanel.add(pageLabel);

        disconnectClientButton = new JButton("断开选中客户端");
        JPanel actionPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        actionPanel.add(disconnectClientButton);

        JPanel bottomControls = new JPanel(new BorderLayout());
        bottomControls.add(actionPanel, BorderLayout.WEST);
        bottomControls.add(paginationPanel, BorderLayout.EAST);
        bottomPanel.add(bottomControls, BorderLayout.SOUTH);

        add(bottomPanel, BorderLayout.SOUTH);

        // 事件
        prevPageButton.addActionListener(e -> changePage(-1));
        nextPageButton.addActionListener(e -> changePage(1));
        disconnectClientButton.addActionListener(e -> disconnectSelectedClient());

        // 初始化分页显示
        clientTableModel.setAll(new ArrayList<>());
    }

    /**
     * 随机生成6位数令牌
     * @return
     */
    private String generateRandomToken() {
        Random random = new Random();
        return String.format("%06d", random.nextInt(1000000));
    }

    private void startServer() {
        try {
            int port = Integer.parseInt(portField.getText());
            int filePort = Integer.parseInt(filePortField.getText());
            String token = tokenField.getText().trim();

            // 验证令牌格式
            if (!token.matches("\\d{6}")) {
                JOptionPane.showMessageDialog(this, "令牌必须是6位数字", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 启动远程控制服务
            server = new RemoteServer(port, token);
            new Thread(server,"eguid-RemoteServer").start();

            // 启动文件传输服务
            fileTransferServer = new FileTransferServer(filePort, token);
            new Thread(fileTransferServer,"eguid-FileTransferServer").start();

            startButton.setEnabled(false);
            stopButton.setEnabled(true);
            uploadStatusLabel.setText("文件传输服务运行中 - 端口: " + filePort);
            statusLabel.setText("服务运行中 - 远程端口: " + port + " 文件端口: " + filePort + " 令牌: " + token);

            // 启动客户端列表轮询（每秒）
            if (clientListTimer != null) {
                clientListTimer.stop();
            }
            clientListTimer = new Timer(1000, e -> refreshClientTable());
            clientListTimer.start();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "启动服务失败: " + ex.getMessage());
        }
    }

    private void stopServer() {
        if (server != null) {
            server.stop();
            server = null;
        }

        if (fileTransferServer != null) {
            fileTransferServer.stop();
            fileTransferServer = null;
        }

        startButton.setEnabled(true);
        stopButton.setEnabled(false);
        uploadStatusLabel.setText("就绪");
        statusLabel.setText("服务已停止");

        if (clientListTimer != null) {
            clientListTimer.stop();
            clientListTimer = null;
        }

        // 清空客户端表格
        clientTableModel.setAll(new ArrayList<>());
        currentPage = 1;
        pageLabel.setText("第 1 页");
    }

    // 添加更新上传状态的方法
    public void setUploadStatus(String status) {
        SwingUtilities.invokeLater(() -> uploadStatusLabel.setText(status));
    }

    // 分页辅助
    private void changePage(int delta) {
        int total = clientTableModel.getTotalCount();
        int totalPages = Math.max(1, (int) Math.ceil(total / (double) PAGE_SIZE));
        currentPage = Math.max(1, Math.min(totalPages, currentPage + delta));
        pageLabel.setText("第 " + currentPage + " 页");
        clientTableModel.setPage(currentPage, PAGE_SIZE);
    }

    private void disconnectSelectedClient() {
        int row = clientTable.getSelectedRow();
        if (row < 0) {
            JOptionPane.showMessageDialog(this, "请先选择一个客户端行");
            return;
        }
        // 当前实现以单连接为主，后续扩展多连接后可依据ID选择断开具体连接
        // 简化：当前服务端仅维护一个连接，调用断开当前客户端
        if (server != null) {
            server.disconnectCurrentClient();
        }
    }

    // 简单表格模型：当前版本演示场景，配合单连接后续可扩展
    private static class ClientTableModel extends AbstractTableModel {
        private final String[] columns = {"ID", "地址", "连接时间"};
        private final java.util.List<Row> all = new ArrayList<>();
        private final java.util.List<Row> pageData = new ArrayList<>();
        private int page = 1;
        private int pageSize = PAGE_SIZE;

        public void setPage(int page, int pageSize) {
            this.page = page;
            this.pageSize = pageSize;
            refreshPage();
            fireTableDataChanged();
        }

        public int getTotalCount() { return all.size(); }

        public void setAll(java.util.List<Row> rows) {
            all.clear();
            if (rows != null) all.addAll(rows);
            refreshPage();
            fireTableDataChanged();
        }

        private void refreshPage() {
            pageData.clear();
            int from = Math.max(0, (page - 1) * pageSize);
            int to = Math.min(all.size(), from + pageSize);
            for (int i = from; i < to; i++) pageData.add(all.get(i));
        }

        @Override public int getRowCount() { return pageData.size(); }
        @Override public int getColumnCount() { return columns.length; }
        @Override public String getColumnName(int column) { return columns[column]; }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Row r = pageData.get(rowIndex);
            switch (columnIndex) {
                case 0: return r.id;
                case 1: return r.address;
                case 2: return r.connectedAt;
                default: return "";
            }
        }

        static class Row {
            final String id;
            final String address;
            final String connectedAt;
            Row(String id, String address, String connectedAt) {
                this.id = id; this.address = address; this.connectedAt = connectedAt;
            }
        }
    }

    // 轮询并刷新表格数据（当前实现展示单连接，可扩展为多连接）
    private void refreshClientTable() {
        if (server == null) {
            return;
        }
        String addr = server.getCurrentClientAddress();
        java.util.List<ClientTableModel.Row> rows = new ArrayList<>();
        if (addr != null && !addr.isEmpty() && !"null".equals(addr)) {
            if (!addr.equals(lastShownAddress)) {
                lastShownAddress = addr;
                lastConnectedAtText = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                        .format(java.time.LocalDateTime.now());
            }
            rows.add(new ClientTableModel.Row("1", addr, lastConnectedAtText));
        } else {
            lastShownAddress = "";
            lastConnectedAtText = "";
        }
        clientTableModel.setAll(rows);
        // 保持当前页有效
        changePage(0);
    }
}
